package com.fenrirtec.aepp.manage.action;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.dto.AttachmentDto;
import com.fenrirtec.aepp.common.service.AttachmentService;
import com.fenrirtec.aepp.common.service.impl.AttachmentServiceImpl;
import com.fenrirtec.aepp.manage.common.action.CommonAction;

public class AttachmentDownloadAction extends CommonAction {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(AttachmentDownloadAction.class);

	private Integer attachmentId;
	private String fileName;
	private String downloadFileName;

	public Integer getAttachmentId() {
        return attachmentId;
    }

    public void setAttachmentId(Integer attachmentId) {
        this.attachmentId = attachmentId;
    }

    public String getFileName() {
		try {
			return new String(fileName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			return fileName;
		}
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getDownloadFileName() {
		return downloadFileName;
	}

	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName;
	}

	public AttachmentDownloadAction() {
	}

	public String download() {
		if (logger.isInfoEnabled()) {
			logger.info("[AttachmentDownloadAction#init] start.");
		}
		
		if (attachmentId != null && attachmentId > 0) {
			AttachmentService service = new AttachmentServiceImpl();
			AttachmentDto attachmentDto = service.searchAttachment(attachmentId);
			String path = attachmentDto.getPath();
			setFileName(path.substring(path.lastIndexOf("/") + 1));
			setDownloadFileName(path);
		}
		
		if (logger.isInfoEnabled()) {
			logger.info("[AttachmentDownloadAction#init] finish.");
		}
		return SUCCESS;
	}

	public InputStream getInputStream() throws Exception {
		return new FileInputStream(getDownloadFileName());
	}
}
